package com.example.mydy;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.example.mydy.model.Project;
import com.example.mydy.model.UserData;
import com.example.mydy.model.UserInfo;
import com.example.mydy.utils.MockDataManager;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Locale;

public class ProjectDetailActivity extends AppCompatActivity {

    private static final String TAG = "ProjectDetailActivity";
    private static final String PREFS_NAME = "MyAppPrefs";
    private static final String KEY_USERNAME = "username";

    private ImageView ivProjectImage;
    private TextView tvProjectTitle;
    private TextView tvProjectDescription;
    private TextView tvProjectPrice;
    private TextView tvPublishedTime;
    private TextView tvProjectContent;
    private TextView tvContentPreview;
    private View lockedContentContainer;
    private Button btnUnlock;
    private TextView tvUnlockInfo;

    private int projectId;
    private String currentUsername;
    private Project currentProject;
    private DecimalFormat priceFormat = new DecimalFormat("¥#,##0.00");
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_project_detail);

        // 初始化视图
        initViews();
        
        // 获取当前用户
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        currentUsername = prefs.getString(KEY_USERNAME, "");

        // 获取项目ID
        projectId = getIntent().getIntExtra("project_id", -1);
        if (projectId == -1) {
            Toast.makeText(this, "无效的项目ID", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 加载项目详情
        loadProjectDetails();
    }

    private void initViews() {
        Toolbar toolbar = findViewById(R.id.toolbar_project_detail);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);

        // 初始化视图引用
        ivProjectImage = findViewById(R.id.iv_project_image);
        tvProjectTitle = findViewById(R.id.tv_project_title);
        tvProjectDescription = findViewById(R.id.tv_project_description);
        tvProjectPrice = findViewById(R.id.tv_project_price);
        tvPublishedTime = findViewById(R.id.tv_published_time);
        tvProjectContent = findViewById(R.id.tv_project_content);
        tvContentPreview = findViewById(R.id.tv_content_preview);
        lockedContentContainer = findViewById(R.id.locked_content_container);
        btnUnlock = findViewById(R.id.btn_unlock);
        tvUnlockInfo = findViewById(R.id.tv_unlock_info);

        // 设置返回按钮点击事件
        ImageButton btnBack = findViewById(R.id.btn_back);
        btnBack.setOnClickListener(v -> finish());

        // 设置解锁按钮点击事件
        btnUnlock.setOnClickListener(v -> confirmUnlock());
    }

    private void loadProjectDetails() {
        // 从数据管理器获取项目
        currentProject = MockDataManager.getProjectById(projectId);
        if (currentProject == null) {
            Toast.makeText(this, "找不到项目", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 设置项目信息
        tvProjectTitle.setText(currentProject.getTitle());
        tvProjectDescription.setText(currentProject.getDescription());
        tvProjectPrice.setText(priceFormat.format(currentProject.getReward()));
        tvPublishedTime.setText("发布时间: " + dateFormat.format(currentProject.getCreatedAt()));

        // 加载项目图片
        // 注意：实际项目中应该使用Glide或Picasso等库
        // Glide.with(this).load(currentProject.getImageUrl()).placeholder(R.drawable.placeholder_image).into(ivProjectImage);
        ivProjectImage.setImageResource(R.drawable.placeholder_image);

        // 检查是否已解锁
        boolean isUnlocked = MockDataManager.hasUnlockedProject(currentUsername, projectId);
        updateContentView(isUnlocked);
    }

    private void updateContentView(boolean isUnlocked) {
        if (isUnlocked) {
            // 已解锁，显示完整内容
            tvProjectContent.setVisibility(View.VISIBLE);
            lockedContentContainer.setVisibility(View.GONE);
            tvProjectContent.setText(Html.fromHtml(currentProject.getArticle()));
        } else {
            // 未解锁，显示预览和解锁按钮
            tvProjectContent.setVisibility(View.GONE);
            lockedContentContainer.setVisibility(View.VISIBLE);
            
            // 设置预览内容（只显示前100个字符）
            String content = currentProject.getArticle();
            String preview = content.length() > 100 ? content.substring(0, 100) + "..." : content + "...";
            tvContentPreview.setText(Html.fromHtml(preview));
            
            // 设置解锁提示
            tvUnlockInfo.setText("解锁后将扣除 " + priceFormat.format(currentProject.getReward()) + " 余额");
        }
    }

    private void confirmUnlock() {
        // 获取用户信息
        UserData userData = MockDataManager.getUserDataStatic(currentUsername);
        if (userData == null) {
            Toast.makeText(this, "获取用户信息失败", Toast.LENGTH_SHORT).show();
            return;
        }

        // 检查余额是否足够
        double balance = userData.getBalance();
        double unlockPrice = currentProject.getReward();
        
        if (balance < unlockPrice) {
            Toast.makeText(this, "余额不足，请先充值", Toast.LENGTH_SHORT).show();
            return;
        }

        // 显示确认对话框
        new AlertDialog.Builder(this)
            .setTitle("确认解锁")
            .setMessage("确定要花费 " + priceFormat.format(unlockPrice) + " 解锁该项目吗？\n解锁后余额将变为 " + priceFormat.format(balance - unlockPrice))
            .setPositiveButton("确定", (dialog, which) -> {
                unlockProject();
            })
            .setNegativeButton("取消", null)
            .show();
    }

    private void unlockProject() {
        boolean success = MockDataManager.unlockProject(currentUsername, projectId, currentProject.getReward());
        if (success) {
            Toast.makeText(this, "解锁成功", Toast.LENGTH_SHORT).show();
            updateContentView(true);
        } else {
            Toast.makeText(this, "解锁失败，请稍后重试", Toast.LENGTH_SHORT).show();
        }
    }
} 